﻿using AiQiuQuan.Sport.Core.WechatPayV3;
using AiQiuQuan.Sport.Core.WechatApi;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApiClientCore.Serialization.JsonConverters;

namespace AiQiuQuan.Sport.Core
{
    /// <summary>
    /// 应用服务注册统一入口
    /// </summary>
    public static class SetupExtension
    {
        /// <summary>
        /// 注入核心服务
        /// </summary>
        /// <param name="services"></param>
        public static void AddServiceCore<TDbContext>(this IServiceCollection services, IConfiguration configuration) where TDbContext : DbContext
        {
            //cors
            services.AddCors(option =>
            {
                option.AddPolicy("aiqiuquan", policy =>
                {
                    policy.AllowAnyOrigin();
                });
            });
            //controller
            services.AddMvc().AddMvcResultFilter().AddJsonOptions(options =>
            {
                //serialize
                options.JsonSerializerOptions.Converters.Insert(0, new StringNullConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss"));
                options.JsonSerializerOptions.Converters.Add(new NumberConverter());
            });
            services.AddHttpClient();
            services.AddHttpContextAccessor();
            // routing url
            services.AddRouting(options => options.LowercaseUrls = true);
            //inject service
            services.RegisterInterfaceService("AiQiuQuan.Sport.*.dll");
            //webapiclientcore
            services.AddWebApiClientCore("AiQiuQuan.Sport.WebClient");
            //mapper
            services.AddMapsterMapper();
            //interceptor
            services.AddAspectService();
            //cache
            services.AddMemoryCache();
            services.AddCaching(configuration);
            //uniqueid config
            configuration.ConfigrureIdOption();
            //dbcontext
            services.AddMsSqlDbContext<TDbContext>(configuration["SqlServerConnectionStr"]);
            ////转后台任务服务
            //services.AddBackgroundJobService(option => { option.ThreadCount = 1; });
            //分布式锁
            services.AddRedLock(configuration);
            //cap服务
            services.AddRedisSqlserverCap<TDbContext>(configuration);
            //注入微信支付V3相关服务
            services.AddWechatPayV3(configuration.GetSection("WechatPayOptions"));
            //注入微信api相关服务
            services.AddWechatApi(configuration.GetSection("WeChatApiOptions"));
            //hangfire定时任务
            services.AddRedisHangfire(configuration["RedisConnStr"]);
            //baseurl
            services.AddSingleton<ApiUrl>();

        }
    }
}
